package frame.Employee;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.EmployeeMapper;
import org.example.pojo.Employee;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class employeeupdate extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession;
    private EmployeeMapper employeeMapper;

    public employeeupdate() {
        sqlSession = MyBatislianjian.getSqlSession();
        employeeMapper = sqlSession.getMapper(EmployeeMapper.class);

        setTitle("修改员工信息");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
        table = new JTable() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return true; // 设置单元格可编辑
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // 设置多选模式

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel();
        JButton updateButton = new JButton("确定修改");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateEmployees(); // 点击确定修改按钮时执行更新操作
            }
        });
        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new EmployeePanel());
            }
        });
        buttonPanel.add(updateButton);
        buttonPanel.add(returnButton);
        this.add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 初始化表格数据
    private void initializeTableData() {
        Object[] columnNames = {"员工编号", "员工姓名", "密码", "等级", "电话", "薪水", "备注"};
        List<Employee> employees = employeeMapper.selectAll();

        // 动态生成数据数组
        Object[][] data = new Object[employees.size()][columnNames.length];
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            data[i][0] = employee.getEid();
            data[i][1] = employee.getEName();
            data[i][2] = employee.getEPas();
            data[i][3] = employee.getElevel();
            data[i][4] = employee.getEtelPhone();
            data[i][5] = employee.getESalary() != null ? employee.getESalary().toString() : "";
            data[i][6] = employee.getOther();
        }

        tableModel = new DefaultTableModel(data, columnNames);
        table.setModel(tableModel);
    }

    // 更新员工信息到数据库
    private void updateEmployees() {
        int rowCount = table.getRowCount();
        boolean hasChanges = false; // 检查是否有任何数据变化

        for (int row = 0; row < rowCount; row++) {
            String eid = ((String) table.getValueAt(row, 0)).trim();
            String eName = ((String) table.getValueAt(row, 1)).trim();
            String ePas = ((String) table.getValueAt(row, 2)).trim();
            String eLevel = ((String) table.getValueAt(row, 3)).trim();
            String eTelPhone = ((String) table.getValueAt(row, 4)).trim();
            String eSalaryStr = ((String) table.getValueAt(row, 5)).trim();
            String other = ((String) table.getValueAt(row, 6)).trim();

            Integer eSalary = null;
            try {
                if (!eSalaryStr.isEmpty()) {
                    eSalary = Integer.parseInt(eSalaryStr);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "薪水字段必须是整数！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 检查关键字段不能为空字符
            if (eid.isEmpty() || eName.isEmpty() || ePas.isEmpty() || eLevel.isEmpty() || eTelPhone.isEmpty()) {
                JOptionPane.showMessageDialog(this, "每一行的员工编号、员工姓名、密码、等级、电话都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 获取原始数据
            Employee originalEmployee = employeeMapper.selectEmployeeByEid(eid);
            if (originalEmployee != null) {
                // 检查数据是否有变化
                if (!originalEmployee.getEName().equals(eName)
                        || !originalEmployee.getEPas().equals(ePas)
                        || !originalEmployee.getElevel().equals(eLevel)
                        || !originalEmployee.getEtelPhone().equals(eTelPhone)
                        || (originalEmployee.getESalary() != null && !originalEmployee.getESalary().equals(eSalary))
                        || (originalEmployee.getESalary() == null && eSalary != null)
                        || !originalEmployee.getOther().equals(other)) {
                    // 更新数据库中的员工信息
                    Employee updatedEmployee = new Employee(eid, eName, ePas, eLevel, eTelPhone, eSalary, other);
                    employeeMapper.updateEmployee(updatedEmployee);
                    hasChanges = true; // 标记有变化
                }
            }
        }

        if (hasChanges) {
            JOptionPane.showMessageDialog(this, "员工信息已更新！", "提示", JOptionPane.INFORMATION_MESSAGE);
            // 刷新表格数据
            refreshTableData();
        } else {
            JOptionPane.showMessageDialog(this, "没有检测到任何更改。", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // 刷新表格数据的方法
    private void refreshTableData() {
        List<Employee> employees = employeeMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (Employee employee : employees) {
            tableModel.addRow(new Object[]{
                    employee.getEid(),
                    employee.getEName(),
                    employee.getEPas(),
                    employee.getElevel(),
                    employee.getEtelPhone(),
                    employee.getESalary() != null ? employee.getESalary().toString() : "",
                    employee.getOther()
            });
        }
    }
}
